<?php
namespace serv\task\purchase;

use L;
use of;
use traits\StockTrait;
use traits\UserTrait;


class purchase
{
    //处理核销入库
    public static function purchaseWarehouse()
    {
        $sql = "SELECT * FROM purchase_warehouse WHERE 1 AND sync = 0 AND source = 0;";
        $result = L::sql($sql, 'purchase');
        if (!empty($result)) {
            //分别以采购单号+SKU及申购单号+sku的维度来判断是否是部分入库还是全部入库
            $purchaseArr = []; //申购单
            $purchaseOrderArr = []; //采购单
            foreach ($result as $v) {
                //更新相应申购单的到货数量
                self::updatePurchase($v);
                //更新相应采购单的到货数量
                self::updatePurchaseOrder($v);
                //更新相应团队的库存数量
                self::updateStock($v);
                //更新核销单的状态
                self::purchaseWarehouseStatus($v);
                $purchaseArr[] = $v['purchase_no'];
                $purchaseOrderArr[] = $v['po_no'];
            }
            $purchaseArr = array_unique($purchaseArr);
            $purchaseOrderArr = array_unique($purchaseOrderArr);
            //更新申购单的状态
            foreach ($purchaseArr as $purchase_no) {
                self::purchaseStatus($purchase_no);
            }

            //更新采购单的状态
            foreach ($purchaseOrderArr as $po) {
                self::purchaseOrderStatus($po);
            }
        }
    }


    //更新采购单的到货数量
    private static function updatePurchase($data)
    {
        $sql = "UPDATE purchase_sku AS a LEFT JOIN purchase AS b ON a.purchase_id = b.purchase_id
                SET a.arrive_qty = a.arrive_qty + {$data['qty']} 
                WHERE 1
                AND b.purchase_no = '{$data['purchase_no']}'
                AND a.sku = '{$data['sku']}'
                AND b.belong = '{$data['belong']}'";
        return L::sql($sql, 'purchase');
    }


    //更新采购单的到数数量
    private static function updatePurchaseOrder($data)
    {
        $sql = "UPDATE purchase_list AS a LEFT JOIN purchase_order AS b ON a.order_id = b.order_id
                SET a.arrive_qty = a.arrive_qty + {$data['qty']} 
                WHERE 1
                AND b.po_no = '{$data['po_no']}'
                AND a.sku = '{$data['sku']}';";
        return L::sql($sql, 'purchase');
    }


    //更新相应团队的到货数量并写入日志信息
    private static function updateStock($data)
    {
        $localWarehouse = of::config('env.DEFAULT_LOCAL_WAREHOUSE');
        //获取库存信息
        $stockInfo = StockTrait::stockId($localWarehouse, $data['sku'], $data['belong']);
        $stockId = !empty($stockInfo) ? $stockInfo['stock_id'] : 0;
        $userInfo = UserTrait::user($data['created_by']);
        $name = !empty($userInfo) ? $userInfo['name'] : '';
        $sql = "UPDATE stock SET stock = stock + {$data['qty']}, available_stock = available_stock + {$data['qty']} WHERE 1 
                AND warehouse_id IN ('".implode("','", $localWarehouse)."') 
                AND sku = '{$data['sku']}'
                AND belong = '{$data['belong']}';";
        L::sql($sql, 'warehouse');

        $created_at = date('Y-m-d H:i:s');
        $updated_at = date('Y-m-d H:i:s');
        $detail = "采购入库,当前库存【入库前: {$stockInfo['stock']} 入库后: ".($stockInfo['stock'] + $data['qty'])."】, 可用库存【入库前: {$stockInfo['available_stock']} 入库后: ".($stockInfo['available_stock'] + $data['qty'])."】";
        $sql = "INSERT INTO stock_logs(stock_id, sku, operator, details, remark, `type`, created_at, updated_at)
                VALUES ('{$stockId}', '{$data['sku']}', '{$name}', '{$detail}', '', '新增', '{$created_at}', '{$updated_at}');";
        L::sql($sql, 'warehouse');
    }

    //更新核销单的状态
    private static function purchaseWarehouseStatus($data)
    {
        $updated_at = date('Y-m-d H:i:s');
        $sql = "UPDATE purchase_warehouse SET sync = 1, updated_at = '{$updated_at}' WHERE 1 AND id = '{$data['id']}';";
        return L::sql($sql, 'purchase');
    }
    
    //处理申购单的状态
    private static function purchaseStatus($purchase_no)
    {
        $sql = "SELECT a.sku, a.qty, a.purchase_qty, a.arrive_qty, b.purchase_id FROM purchase_sku AS a LEFT JOIN purchase AS b ON a.purchase_id = b.purchase_id 
                WHERE 1 
                AND b.purchase_no = '{$purchase_no}';";
        $result = L::sql($sql, 'purchase');
        if (!empty($result)) {
            $checkArr = [];
            foreach ($result as $check) {
                //如果到货数量小于下单数量
                if ($check['arrive_qty'] < $check['purchase_qty']) {
                    $checkArr[] = $check['purchase_id'];
                }
            }

            if (!empty($checkArr)) {
                //有未完全到货的情况
                $sql = "UPDATE purchase SET status = 60 WHERE 1 AND purchase_no = '{$purchase_no}';";
            } else {
                //全部到货
                $sql = "UPDATE purchase SET status = 70 WHERE 1 AND purchase_no = '{$purchase_no}';";
            }
            return L::sql($sql, 'purchase');
        }
    }

    //更新采购单的状态
    public static function purchaseOrderStatus($po_no)
    {
        $sql = "SELECT a.sku, a.qty, a.arrive_qty, b.order_id FROM purchase_list AS a LEFT JOIN purchase_order AS b ON a.order_id = b.order_id 
                WHERE 1 
                AND b.po_no = '{$po_no}';";
        $result = L::sql($sql, 'purchase');
        if (!empty($result)) {
            $checkArr = [];
            foreach ($result as $check) {
                //如果到货数量小于下单数量
                if ($check['arrive_qty'] < $check['qty']) {
                    $checkArr[] = $check['order_id'];
                }
            }

            if (!empty($checkArr)) {
                //有未完全到货的情况
                $sql = "UPDATE purchase_order SET status = 30 WHERE 1 AND po_no = '{$po_no}';";
            } else {
                //全部到货
                $sql = "UPDATE purchase_order SET status = 40 WHERE 1 AND po_no = '{$po_no}';";
            }
            return L::sql($sql, 'purchase');
        }
    }



}